//
//  HttpConnectTools.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/2/12.
//

import UIKit

import Alamofire
import SwiftyJSON

import Photos
import AssetsLibrary
import MediaPlayer
import CoreTelephony
import CoreLocation
import AVFoundation



var sessionManager:Session!


class HttpConnectTools: NSObject {
    
    
    static let share: HttpConnectTools = {
        let tools = HttpConnectTools()
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 30
        sessionManager = Session.init(configuration: config)

        return tools
    }()
}

extension HttpConnectTools
{
    func request(urlString: String, parameters: [String:AnyObject]?, finished: @escaping (_ result: String?, _ error: NSError?) -> Void){
        
        
        
    
        let resultCallBack = {(response:AFDataResponse<String>) in
            switch response.result{
            case .success(_):
                var decryptStr = ""
                let responseStr = NSString.init(data: response.data ?? Data(), encoding: String.Encoding.utf8.rawValue) ?? ""
                decryptStr = responseStr as String
                let json = JSON(parseJSON: decryptStr)
                    debugPrint("url       = \(urlString)")
                
//                let retCode = json["retCode"].stringValue
//                if(retCode == "9998"){//过期
//                    loginOut(text: "登录已过期，请重新登录")
//                    return
//                }
//                if(retCode == "0002"){//刷新
//                    refreshToken()
//                }
                
                debugPrint("param     =",jhToJson(parameters ?? [:]))
                debugPrint("response  =",json)
                //回调
                finished(decryptStr, nil)
                
            case.failure(let error):
                debugPrint("connection error = \(error.localizedDescription)")
                let err = NSError.init(domain: "error", code: -10001, userInfo: ["errorinfo":"网络连接失败"])
                self.noNetworking()
                finished(nil,err)
                break
            }
        }
        
        let token = kUserToken
        var headers: HTTPHeaders = []
        
        let idfv:String = UIDevice.current.identifierForVendor?.uuidString ?? ""
//        print("---idfv\(idfv!)")
//        headers["idfv"] = idfv
        print("---token:\(token)")
        
        if(kIsLogin){
            headers = [
                "Content-Type":"application/json",
                "token":token,
                "idfv":idfv
            ]
        }else{
            headers = [
                "Content-Type":"application/json",
                "idfv":idfv
            ]
        }
    
//        let config = URLSessionConfiguration.default
//        config.timeoutIntervalForRequest = 30
        let data = try? JSONSerialization.data(withJSONObject: parameters ?? [], options: [])
        var request = try? URLRequest(url: URL(string: urlString)!, method: .post, headers: headers)
        request?.httpBody = data
//        sessionManager = Session.init(configuration: config)
        sessionManager.request(request!).responseString(completionHandler: resultCallBack)
        
    }
    
    //第一次装app无气泡提示
    func noNetworking() {
        let key = kUserDefaults.value(forKey: kNetworking) as? String ?? ""
        if(key.count > 0){
            dissmissToTast(msg: "网络连接失败")
        }else{
            kUserDefaults.setValue("网络连接失败", forKey: kNetworking)
        }

    }

}

//dic TO JSON
func jhToJson(_ dict: [String:AnyObject]) -> NSString{
    let data = try? JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.init(rawValue: 0))
    let json = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) ?? ""
    return json
}

/// 检测是否开启联网
func hw_openEventServiceWithBolck(action :@escaping ((Bool)->())) {
    let cellularData = CTCellularData()
    cellularData.cellularDataRestrictionDidUpdateNotifier = { (state) in
        if state == CTCellularDataRestrictedState.restrictedStateUnknown ||  state == CTCellularDataRestrictedState.notRestricted {
            action(false)
        } else {
            action(true)
        }
    }
    let state = cellularData.restrictedState
    if state == CTCellularDataRestrictedState.restrictedStateUnknown ||  state == CTCellularDataRestrictedState.notRestricted {
        action(false)
    } else {
        action(true)
    }
}


func refreshToken() {
    let param = [
        "oldToken": kUserToken
            ] as [String:AnyObject]
    HttpConnectTools.share.request(urlString: APIUrl.share.refreshToken_URL, parameters: param) { (result, error) in
    }
    
}


func uploadImage(url: String, image: UIImage, params: [String:String], finish: @escaping((_ result: String?, _ error: NSError?) -> ())){
    //请求头
    var headers: HTTPHeaders = []
    
    let idfv:String = UIDevice.current.identifierForVendor?.uuidString ?? ""
    let token = kUserToken
    print("---token:\(token)")
    
    if(kIsLogin){
        headers = [
            "Content-Type":"application/json",
            "token":token,
            "idfv":idfv
        ]
    }else{
        headers = [
            "Content-Type":"application/json",
            "idfv":idfv
        ]
    }
    let imgData = image.jpegData(compressionQuality: 0.1)
    sessionManager.upload(multipartFormData: { multiPart in
        multiPart.append(imgData!, withName: "file", fileName: "aa.jpg", mimeType: "image/jpg")
        params.forEach { (key,value) in
            multiPart.append(value.data(using: .utf8)!, withName: key)
        }
    }, to: url, method: .post, headers: headers, interceptor: nil, fileManager:.default).responseString { (response) in
        switch response.result {
        case .success:
            let responseStr = NSString.init(data: response.data ?? Data(), encoding: String.Encoding.utf8.rawValue) ?? ""
            debugPrint("responseStr       = :", responseStr)
            var decryptStr = ""
            decryptStr = responseStr as String
            let json = JSON(parseJSON: decryptStr)

            debugPrint("url       = \(url)")
            debugPrint("param     =",jhToJson(params as [String:AnyObject]))
            debugPrint("response  =",json)
            finish(decryptStr, nil)
//            if let code = json["retCode"].int{
//                if code == 0000{
//                    finish(decryptStr, nil)
//                }else{
//                    let message = json["message"].string ?? ""
//                    let err = NSError.init(domain: "error", code: code, userInfo: ["errorinfo":message])
//                    finish(nil, err)
//                }
//            }
//            else{
//                let err = NSError.init(domain: "error", code: -1111, userInfo: ["errorinfo":"请求超时"])
//                finish(nil, err)
//            }
        case .failure:
            let err = NSError.init(domain: "error", code: -10001, userInfo: ["errorinfo":"网络连接失败"])
            finish(nil, err)
        }
    }
}
